<template>
  <div class="forum-list-container">
    <!-- 顶部操作栏 -->
    <div class="top-actions">
      <el-button type="primary" icon="el-icon-edit" @click="showCreateDialog">发布帖子</el-button>
      <el-button 
        type="warning" 
        icon="el-icon-download" 
        @click="exportPosts"
        v-if="false && postList.length > 0"
        style="margin-left: 10px;">
        导出帖子
      </el-button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card shadow="hover">
        <div class="search-form">
          <!-- 标题搜索 -->
          <div class="search-item">
            <label>标题</label>
            <el-input 
              v-model="searchForm.title" 
              placeholder="请输入标题关键词" 
              clearable
              @clear="handleSearch">
            </el-input>
          </div>

          <!-- 关键词搜索 -->
          <div class="search-item">
            <label>关键词</label>
            <el-input 
              v-model="searchForm.keywords" 
              placeholder="请输入关键词" 
              clearable
              @clear="handleSearch">
            </el-input>
          </div>

          <!-- 搜索按钮 -->
          <div class="search-buttons">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
          </div>
        </div>

        <!-- 筛选按钮区域 -->
        <div class="filter-section">
          <div class="filter-group">
            <label>发布者：</label>
            <div class="filter-buttons">
              <div 
                class="filter-btn" 
                :class="{ active: searchForm.publisher === '' }"
                @click="filterByPublisher('')">
                全部
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.publisher === 'me' }"
                @click="filterByPublisher('me')">
                我的帖子
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.publisher === 'others' }"
                @click="filterByPublisher('others')">
                他人帖子
              </div>
            </div>
          </div>

          <div class="filter-group">
            <label>排序方式：</label>
            <div class="filter-buttons">
              <div 
                class="filter-btn" 
                :class="{ active: searchForm.orderBy === '' }"
                @click="filterByOrder('')">
                默认排序
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.orderBy === 'like' }"
                @click="filterByOrder('like')">
                点赞最多
              </div>
              <div 
                class="filter-btn"
                :class="{ active: searchForm.orderBy === 'comment' }"
                @click="filterByOrder('comment')">
                评论最多
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 帖子列表 -->
    <div class="posts-grid">
      <el-card 
        v-for="post in postList" 
        :key="post.id" 
        class="post-card" 
        shadow="hover"
        @click.native="viewPostDetail(post.id)">
        <!-- 帖子图片 -->
        <div class="post-image">
          <img 
            v-if="post.images && !post.imageLoadError" 
            :src="getFirstImage(post.images)" 
            alt="帖子封面"
            @error="handleImageLoadError(post)">
          <div v-else class="no-image">
            <i class="el-icon-picture-outline"></i>
          </div>
        </div>

        <!-- 帖子信息 -->
        <div class="post-info">
          <div class="post-title">{{ post.title }}</div>
          <div class="post-description">{{ post.description }}</div>
          <div class="post-keywords" v-if="post.keywords">
            <el-tag 
              v-for="(keyword, index) in post.keywords.split(',')" 
              :key="index"
              size="mini"
              type="info">
              {{ keyword }}
            </el-tag>
          </div>
        </div>

        <!-- 帖子底部 -->
        <div class="post-footer">
          <div class="post-author">
            <i class="el-icon-user"></i>
            <span>{{ post.username }}</span>
          </div>
          <div class="post-stats">
            <span class="stat-item">
              <i class="el-icon-thumb"></i>
              {{ post.likeCount }}
            </span>
            <span class="stat-item">
              <i class="el-icon-chat-dot-round"></i>
              {{ post.commentCount }}
            </span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="postList.length === 0" description="暂无帖子"></el-empty>

    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        background
        layout="total, prev, pager, next, sizes"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[8, 12, 16, 20]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange">
      </el-pagination>
    </div>

    <!-- 发布帖子对话框 -->
    <el-dialog 
      title="发布帖子" 
      :visible.sync="createDialogVisible" 
      width="700px"
      :close-on-click-modal="false">
      <el-form :model="postForm" :rules="postRules" ref="postForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="postForm.title" placeholder="请输入帖子标题"></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="postForm.description" 
            type="textarea" 
            :rows="2"
            placeholder="请输入帖子描述（简短概括）">
          </el-input>
        </el-form-item>

        <el-form-item label="正文" prop="content">
          <el-input 
            v-model="postForm.content" 
            type="textarea" 
            :rows="8"
            placeholder="请输入帖子正文内容">
          </el-input>
        </el-form-item>

        <el-form-item label="关键词" prop="keywords">
          <el-input 
            v-model="postForm.keywords" 
            placeholder="请输入关键词，多个关键词用英文逗号分隔">
          </el-input>
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            action="http://47.97.154.151:18001/api/file/upload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :file-list="fileList"
            list-type="picture-card"
            :limit="5">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">最多上传5张图片</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreatePost">发布</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPostList, createPost } from '@/api/forum'

export default {
  name: 'UserForumList',
  data() {
    return {
      searchForm: {
        title: '',
        keywords: '',
        publisher: '',
        orderBy: ''
      },
      postList: [],
      currentPage: 1,
      pageSize: 12,
      total: 0,
      createDialogVisible: false,
      postForm: {
        title: '',
        description: '',
        content: '',
        keywords: '',
        images: ''
      },
      postRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入正文', trigger: 'blur' }
        ]
      },
      fileList: [],
      imageUrls: []
    }
  },
  mounted() {
    this.loadPostList()
  },
  methods: {
    // 加载帖子列表
    async loadPostList() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const userId = userInfo.id
        const params = {
          ...this.searchForm,
          userId: userId,
          page: this.currentPage,
          size: this.pageSize
        }
        
        const response = await getPostList(params)
        if (response.data.code === 200) {
          const data = response.data.data
          this.postList = data.list
          this.total = data.total
        }
      } catch (error) {
        console.error('加载帖子列表失败', error)
        this.$notify.error({
          title: '错误',
          message: '加载帖子列表失败'
        })
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadPostList()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        title: '',
        keywords: '',
        publisher: '',
        orderBy: ''
      }
      this.currentPage = 1
      this.loadPostList()
    },

    // 按发布者筛选
    filterByPublisher(publisher) {
      this.searchForm.publisher = publisher
      this.currentPage = 1
      this.loadPostList()
    },

    // 按排序方式筛选
    filterByOrder(orderBy) {
      this.searchForm.orderBy = orderBy
      this.currentPage = 1
      this.loadPostList()
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadPostList()
    },

    // 页码改变
    handlePageChange(page) {
      this.currentPage = page
      this.loadPostList()
    },

    // 获取第一张图片
    getFirstImage(images) {
      if (!images) return ''
      const imageArray = images.split(',')
      return imageArray[0]
    },

    // 查看帖子详情
    viewPostDetail(id) {
      this.$router.push({
        path: '/user/forum/detail',
        query: { id }
      })
    },

    // 显示发布对话框
    showCreateDialog() {
      this.createDialogVisible = true
      this.postForm = {
        title: '',
        description: '',
        content: '',
        keywords: '',
        images: ''
      }
      this.fileList = []
      this.imageUrls = []
    },

    // 图片上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.imageUrls.push(response.data)
        this.postForm.images = this.imageUrls.join(',')
      } else {
        this.$notify.error({
          title: '错误',
          message: '图片上传失败'
        })
      }
    },

    // 删除图片
    handleRemove(file, fileList) {
      // 从imageUrls中删除对应的URL
      const index = this.fileList.indexOf(file)
      if (index > -1) {
        this.imageUrls.splice(index, 1)
        this.postForm.images = this.imageUrls.join(',')
      }
      this.fileList = fileList
    },

    // 发布帖子
    handleCreatePost() {
      this.$refs.postForm.validate(async (valid) => {
        if (valid) {
          try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'))
            const userId = userInfo.id
            const response = await createPost(this.postForm, userId)
            
            if (response.data.code === 200) {
              this.$notify.success({
                title: '成功',
                message: '发布成功'
              })
              this.createDialogVisible = false
              this.loadPostList()
            } else {
              this.$notify.error({
                title: '错误',
                message: response.data.message || '发布失败'
              })
            }
          } catch (error) {
            console.error('发布帖子失败', error)
            this.$notify.error({
              title: '错误',
              message: '发布帖子失败'
            })
          }
        }
      })
    },
    handleImageLoadError(post) {
      this.$set(post, 'imageLoadError', true);
    },
    
    // 导出帖子功能 - 预留功能
    exportPosts() {
      if (this.postList.length === 0) {
        this.$notify({
          title: '提示',
          message: '没有可导出的帖子',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      // 导出功能暂未实现
      if (false) {
        const data = this.postList.map(post => ({
          title: post.title,
          description: post.description,
          author: post.username,
          likeCount: post.likeCount,
          commentCount: post.commentCount
        }));
        
        // 这里应该是导出逻辑
        console.log('导出数据:', data);
      }
    },
    
    // 批量操作帖子 - 预留功能
    batchOperatePosts(operation) {
      // 批量操作功能暂未实现
      if (false && this.selectedPosts.length > 0) {
        switch (operation) {
          case 'delete':
            // 删除逻辑
            break;
          case 'publish':
            // 发布逻辑
            break;
          default:
            break;
        }
      }
    }
  }
}
</script>

<style scoped>
.forum-list-container {
  padding: 20px;
  min-height: calc(100vh - 130px);
}

.top-actions {
  margin-bottom: 20px;
  text-align: right;
}

.search-section {
  margin-bottom: 30px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: flex-end;
  margin-bottom: 20px;
}

.search-item {
  flex: 1;
  min-width: 200px;
}

.search-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.filter-group {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-group label {
  font-weight: 500;
  color: #606266;
  margin-right: 15px;
  white-space: nowrap;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-btn {
  padding: 8px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
  color: #606266;
  font-size: 14px;
}

.filter-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.filter-btn.active {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}

.posts-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.post-card {
  cursor: pointer;
  transition: all 0.3s;
  height: 420px;
  display: flex;
  flex-direction: column;
}

.post-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.post-card >>> .el-card__body {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.post-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.post-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 60px;
}

.post-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.post-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.post-description {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  flex: 1;
}

.post-keywords {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.post-footer {
  padding: 12px 15px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafafa;
}

.post-author {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 13px;
}

.post-author i {
  margin-right: 5px;
}

.post-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 13px;
}

.stat-item i {
  margin-right: 3px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

@media (max-width: 1600px) {
  .posts-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 1200px) {
  .posts-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .posts-grid {
    grid-template-columns: 1fr;
  }
}
</style>

